package com.cduestc.weatheractivity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.cduestc.sqllite.DataDeal;
import com.cduestc.sqllite.MySqlLite;
import com.cduestc.tools.GetDataFromNet;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Search extends AppCompatActivity implements DataDeal {

    private ImageButton ibBackManageCity,ibSearchNow,ibAddCityNow;
    private Button btnAll;
    private EditText etInputCityName,etAddCityName,etAddCityCode;

    private String URl_SEARCH = "http://t.weather.itboy.net/api/weather/city/";
    private GetDataFromNet getDataFromNet = new GetDataFromNet();
    private Handler handler1 = new Handler();
    private String datas = "";
    private TextView tvShowPartData,tvBackData;
    private ConnectivityManager connectivityManager;
    private boolean isConn;
    private String cityMsg = "",recodeName = "",recodeCode = "";
    private MySqlLite mySqlLite;
    SQLiteDatabase sdb;
    boolean check = false;
    int flag = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        mySqlLite = new MySqlLite(this,"c1",null,1);
        sdb = mySqlLite.getWritableDatabase();

        ibSearchNow = this.findViewById(R.id.ibSearchNow);
        ibBackManageCity = this.findViewById(R.id.ibBackManageCity);
        btnAll = this.findViewById(R.id.btnAll);
        etInputCityName = this.findViewById(R.id.etInputCityName);
        ibAddCityNow = this.findViewById(R.id.ibAddCityNow);
        tvShowPartData = this.findViewById(R.id.tvShowPartData);
        etAddCityCode = this.findViewById(R.id.etAddCityCode);
        etAddCityName = this.findViewById(R.id.etAddCityName);
        tvBackData = this.findViewById(R.id.tvBackData);
        Resources res = getResources();
        String[] city = res.getStringArray(R.array.city_name);
        String[] code = res.getStringArray(R.array.city_code);

//        System.out.println(city.length);
//        for(;flag < city.length; flag++) {
//            System.out.println(city[flag]);
//        }
        ibBackManageCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Search.this,ManageCity.class);
                startActivity(intent);
                finish();
            }
        });

        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                tvShowPartData.setText(datas);
                etAddCityCode.setText(recodeCode);
                etAddCityName.setText(recodeName);
            }
        };

        ibSearchNow.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
               String name = etInputCityName.getText().toString().trim();

               if(name.equals("")){
                   Toast.makeText(Search.this, "请输入要查询的城市名", Toast.LENGTH_SHORT).show();
                   return;
               }else{
                   for(int i = 0; i < city.length; i++){
                       if(name.equals(city[i])){
                           System.out.println("check" + check);
                           check = true;
                           tvBackData.setText(queryData(code[i]));
                           flag = i;
                           break;
                       }
                   }
                   if(check == false){
                       Toast.makeText(Search.this, "输入的城市可能不存在或者暂时没有收录，点击下方按钮查看所有已经收录了的城市", Toast.LENGTH_LONG).show();
                       return;
                   }
               }

                //请求网络数据
                new Thread() {
                    @Override
                    public void run() throws NullPointerException{
                        super.run();

                        if(check == false){
                            return;
                        }

                        String findCode = code[flag];
                        String cityCode = URl_SEARCH + findCode;

                        cityMsg = getDataFromNet.requestUrl(cityCode, checkNet());
                        if(cityMsg != null) {
                            JsonParser jsonParser = new JsonParser();
                            JsonObject jsonObject = jsonParser.parse(cityMsg).getAsJsonObject();
                            JsonObject jsonData1 = jsonObject.get("cityInfo").getAsJsonObject();
                            JsonObject jsonData2 = jsonObject.get("data").getAsJsonObject();

                            String city = jsonData1.get("city").getAsString();
                            String cityKey = jsonData1.get("citykey").getAsString();

                            String wendu = jsonData2.get("wendu").getAsString() + "℃";
                            String ganmao = jsonData2.get("ganmao").getAsString();

                            recodeCode = cityKey;
                            recodeName = city;

                            datas = city + "   " +
                                    cityKey + "\n" +
                                    "———————————" + "\n" +
                                    "温度：" + wendu + "\n" +
                                    "提示：" +ganmao;

                            flag = 0;
                            check = false;
                        }else{
                            flag = 0;
                            check = false;
                            datas = "请检查网络连接";
                        }
                        handler1.post(runnable1);
                    }
                }.start();
            }
        });

        btnAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //View viewShowCitys = View.inflate(Search.this,R.layout.activity_city_names,null);
                AlertDialog.Builder builder = new AlertDialog.Builder(Search.this);
                ArrayAdapter adapter = ArrayAdapter.createFromResource(Search.this,R.array.city_name,android.R.layout.simple_list_item_1);
                //ListView lvChoiceCity = viewShowCitys.findViewById(R.id.lvChoiceCity);
                //lvChoiceCity.setAdapter(adapter);
                builder.setIcon(R.drawable.icon_all)
                        .setTitle(" 查看所有")
                        .setAdapter(adapter, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String cityName = adapter.getItem(i).toString();
                                etInputCityName.setText(cityName);
                            }
                        })
                        .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        })
                        .create()
                        .show();
            }
        });

        ibAddCityNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String cName = etAddCityName.getText().toString().trim();
                String cCode = etAddCityCode.getText().toString().trim();
                if(cName.equals("")){
                    Toast.makeText(Search.this, "请输入城市名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(cCode.equals("")){
                    Toast.makeText(Search.this, "请输入城市ID", Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(Search.this, addData(cCode,cName), Toast.LENGTH_SHORT).show();
                etAddCityName.setText("");
                etAddCityCode.setText("");
            }
        });

    }
    //检查网络
    public boolean checkNet() {
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
            isConn = true;
        } else {
            isConn = false;
        }
        return isConn;
    }

    //实现接口
    @Override
    public String addData(String citycode,String name) {

        Cursor cursor = sdb.query("mycitys",new String[]{"_id","cid","cityname"},"cityname=? and cid=?",new String[]{name,citycode},null,null,null);
        if(cursor.getCount() == 0){
            ContentValues con = new ContentValues();
            con.put("cid",citycode);
            con.put("cityname",name);
            sdb.insert("mycitys",null,con);
            return "添加成功";
        }else{
            return "该城市已添加，请勿重复添加";
        }
    }

    @Override
    public String queryData(String code) {

        Cursor cursor = sdb.query("mycitys",new String[]{"_id","cid","cityname"},"cid=?",new String[]{code},null,null,null);
        if(cursor.getCount() == 0){
            return "没有查到相关信息";
        }else{
            while(cursor.moveToNext()){
                int onlyId = cursor.getInt(0);
                String cId = cursor.getString(1);
                String cName = cursor.getString(2);
                return "ID        ：" + onlyId + "\n" + "城市名：" + cName + "\n" + "城市ID：" + cId;
            }
        }
        return null;
    }

    //本类中用不着
    @Override
    public String delData(String name) {
        return null;
    }
}